<?php
/**
 * Get date
 * 
 * @param  $strDate
 * @param  $strFormat
 * @return string
 * @author 李鑫辉
 */
function get_date( $strDate = '', $strFormat = 'Y-m-d' ) {

    if ( empty($strDate) ) {

        return date('Y-m-d H:i:s');
        
    } else if ( $strDate == '0000-00-00 00:00:00' ) {
        
        return '';
    }
    
    return date($strFormat, strtotime($strDate));
}

/**
 * Set array key
 * Changes in two-dimensional array, to do with the specified key name
 * 
 * @param  $arrData
 * @param  $strKey
 * @param  $strValue
 * @return array
 * @author 李鑫辉
 */
function set_array_key( $arrData, $strKey = 'id', $strValue = '' ) {
    
    if ( ! is_array($arrData) ) {
        return false;
    }
    
    $arr_result = array();
    foreach ( $arrData as $key => $sub ) {
        $arr_result[$sub[$strKey]] = $strValue ? $sub[$strValue] : $sub;
    }
    
    return $arr_result;
}

/**
 * Set array combine
 * 
 * @param  $arrKeys
 * @param  $arrValues
 * @param  $blnCheckEmpty
 * @return array
 * @author 李鑫辉
 */
function set_array_combine( $arrKeys, $arrValues = '', $blnCheckEmpty = true  ) {
    
    $arr_values = $arrValues ? $arrValues : $arrKeys;
    
    if ( $blnCheckEmpty && empty($arrKeys[0]) ) {
        
        return array();
    }
    
    return array_combine($arrKeys, $arr_values);
}

/**
 * Get range array
 * 
 * @param  $intStart
 * @param  $intEnd
 * @param  $intStep
 * @return string
 * @author 李鑫辉
 */
function get_range_array( $intStart = 1, $intEnd = 100, $intStep = 1 ) {

    return range($intStart, $intEnd, $intStep);
}

/**
 * Write error msg
 * 
 * @param  integer $intStatus
 * @param  mixed   $strMsg
 * @return void
 * @author andy
 */
function output_json_error( $intStatus, $strMsg = '' ) {
    
    echo json_encode(array('statusCode'=>$intStatus, 'message'=>$strMsg));
    exit;
}

/**
 * Write msg
 * 
 * @param  $strMsg
 * @param  $blnCloseWin
 * @return void
 * @author andy
 */
function output_json_info( $strMsg = '', $blnCloseWin = true ) {
    
    $str_call_back_type = $blnCloseWin ? 'closeCurrent' : '';
    echo json_encode(array('statusCode'=>200, 'message'=>$strMsg, 'callbackType'=>$str_call_back_type));
    exit;
}

/**
 * Fetch url
 * 
 * @param  $strUrl
 * @param  $strPost
 * @param  $intTimeout
 * @return string
 * @author andy
 */
function fetch_url( $strUrl, $strPost = '', $intTimeout = 10 ) {

    static $curl_options = array(
        CURLOPT_RETURNTRANSFER  => TRUE,
        CURLOPT_SSL_VERIFYPEER  => FALSE,
        CURLOPT_HTTPHEADER      => array('Expect:'),
        CURLOPT_USERAGENT       => 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0)',
        CURLOPT_TIMEOUT         => 5 // The maximum number of seconds to allow cURL functions to execute. 
    );

    $ch = curl_init($strUrl);
    curl_setopt_array($ch, $curl_options);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $strPost);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $intTimeout);
    $ret = curl_exec($ch);
    curl_close($ch);

    return $ret;
}

/**
 * Set post
 * 
 * @param  $strKey
 * @param  $mixVal
 * @param  $blnCheckEmpty
 * @param  $blnCheckValEmpty
 * @return bool
 * @author andy
 */
function set_post( $strKey, $mixVal, $blnCheckEmpty = true, $blnCheckValEmpty = false ) {
    
    if ( $blnCheckEmpty && empty($_POST[$strKey]) ) {
        return false;
    } 
    
    if ( ! $blnCheckValEmpty || ! empty($mixVal) ) {
        $_POST[$strKey] = is_null($mixVal) ? 0 : $mixVal;
    }
    
    return true;
}

/**
 * Get current url
 * 
 * @param  void
 * @return void
 * @author andy
 */
function get_current_url() {
    
    return 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
}

/**
 * Ftp
 * 
 * @param  $strLocalFileName
 * @param  $strRemoteFileName
 * @return void
 * @author andy
 */
function ftp( $strLocalFileName, $strRemoteFileName ) {
    
    if ( PHP_ENVIRONMENT != 'production' ) {
        return true;
    }
    
    $res_ftp = ftp_connect(C('FTP_HOST'));
    $bln_res = ftp_login($res_ftp, C('FTP_NAME'), C('FTP_PWD'));

    $arr_dir = explode('/', $strRemoteFileName, -1);
    if ( count($arr_dir) ) {
        ftp_chdir($res_ftp, C(FTP_PATH));
        
        foreach ( $arr_dir as $val ) {
            if ( ! $val ) {
                continue;
            }
            
            ftp_mkdir($res_ftp, $val);
            ftp_chdir($res_ftp, $val);
        }
    }

    ftp_pasv($res_ftp, true);
    $bln_res = ftp_put($res_ftp, basename($strRemoteFileName), C(IMAGE_UPLOAD) . $strLocalFileName, FTP_BINARY);

    ftp_close($res_ftp);
    
    return $bln_res;
}

/**
 * Upload file
 * 
 * @param  $intSize
 * @param  $arrAllowExts
 * @return array
 * @author andy
 */
function upload_file( $intSize = 3145728, $arrAllowExts = array('jpg', 'gif', 'png', 'jpeg') ) {
    
    import('ORG.Net.UploadFile');
    
    $obj_upload             = new UploadFile();
    $obj_upload->maxSize    = $intSize;
    $obj_upload->allowExts  = $arrAllowExts;
    $obj_upload->savePath   = C('IMAGE_UPLOAD');
    $obj_upload->autoSub    = true;
    $obj_upload->subType    = C('IMAGE_SUBTYPE');
    $obj_upload->dateFormat = C('IMAGE_DATEFORMAT');
    
    if( ! $obj_upload->upload() ) {
        return array('status'=>-1, 'content'=>$obj_upload->getErrorMsg());
    }
    
    return array('status'=>0, 'content'=>$obj_upload->getUploadFileInfo());
}

/**
 * Check upload file
 * 
 * @param  void
 * @return bool
 * @author andy
 */
function check_upload_file() {
    
    if ( $_FILES ) {
        foreach ( $_FILES as $sub ) {
            if ( ! empty($sub['name']) ) {
                return true;
            }
        }
    }
    
    return false;
}

/**
 * Get status txt
 * 
 * @param  $intStatus
 * @param  $strStatusType
 * @return mix
 * @author andy
 */
function get_status_txt( $intStatus, $strStatusType = 'default' ) {

    $arr_status = D('Common')->get_status($strStatusType);

    return $arr_status[$intStatus];
}

/**
 * Log db
 * 
 * @param  $strMethod
 * @param  $strParams
 * @param  $strDescription
 * @param  $strRemark
 * @return bool
 * @author andy
 */
function log_db( $strMethod, $strParams = '', $strDescription = '', $strRemark = '' ) {
    
    return D('SysLog')->add($strMethod, $strParams, $strDescription, $strRemark);
}

/**
 * Get image url
 * 
 * @param  $strImgUrl
 * @return string
 * @author 李鑫辉
 */
function get_img_url( $strImgUrl ) {

    if ( empty($strImgUrl) ) {
        return false;
    }
    
    if ( PHP_ENVIRONMENT != 'production' ) {
        return stripos($strImgUrl, 'http://') !== false ? $strImgUrl : C('IMAGE_UPLOAD') . $strImgUrl;
    }
    
    return stripos($strImgUrl, 'http://') !== false ? $strImgUrl : C('IMAGE_HOST') . $strImgUrl;
}

/**
 * Show image
 * 
 * @param  $strImgUrl
 * @param  $strClass
 * @return string
 * @author 李鑫辉
 */
function show_img( $strImgUrl, $strClass = 'list_img' ) {

    $str_img_url = get_img_url($strImgUrl);
    
    return '<a href="' . $str_img_url . '" target="_blank"><img src="' . $str_img_url . '" alt="图片不存在" class="' . $strClass . '"/></a>';
}

/**
 * Call action
 * 
 * |call_action=ActionMethod,ActionParams
 * |call_action=get_field_info_txt,source_type
 * 
 * @param  void
 * @return string
 * @author 李鑫辉
 */
function call_action() {

    $arr_args   = func_get_args();

    $str_class  = MODULE_NAME . 'Action';
    $obj_class  = new $str_class; 
    $str_method = $arr_args[1];
    $arr_params = array_slice($arr_args, 2);
    $arr_params = count($arr_params) > 1 ? $arr_params : $arr_params[0];
    $mix_value  = $arr_args[0];

    return $obj_class->$str_method($mix_value, $arr_params);
}

/**
 * Call model
 * 
 * |call_model=ModelName,ModelMethod,ModelParams
 * |call_model=DataGroup,get_info_by_pk,group_name
 * 
 * @param  void
 * @return string
 * @author 李鑫辉
 */
function call_model() {

    $arr_args   = func_get_args();
    $mix_val    = $arr_args[0];
    $str_model  = $arr_args[1];
    $str_method = $arr_args[2] ? $arr_args[2] : 'get_info_by_pk';
    $arr_params = array_slice($arr_args, 3);
    $arr_params = count($arr_params) > 1 ? $arr_params : $arr_params[0];

    return D($str_model)->$str_method($mix_val, $arr_params);
}

/**
 * Lookup
 * 
 * {$str_lookup|lookup=TableName,Width,Height}
 * {$str_lookup|lookup=data_group,1000,600}
 * 
 * @param  void
 * @return string
 * @author 李鑫辉
 */
function lookup() {

    $arr_lookup = array(
                        'data_staff_basic'             => '/attendance/data_staff_basic/lookup',
                        'data_company_basic'           => '/attendance/data_company_basic/lookup',
                        'data_company_department'      => '/attendance/data_company_department/lookup',
                        'data_company_station'         => '/attendance/data_company_station/lookup',
                  );
    $arr_args   = func_get_args();
    $mix_val    = $arr_args[0];
    $str_table  = $arr_args[1];
    $int_width  = $arr_args[2] ? $arr_args[2] : 1000;
    $int_height = $arr_args[3] ? $arr_args[3] : 500;

    return '<a href="' . $arr_lookup[$str_table] . '" lookupgroup="' . $str_table . '" class="btnLook" width="' . $int_width . '" height="' . $int_height . '">查找带回</a>';
}

/**
 * Detail
 * 
 * {$str_val|detail=TableName,Width,Height}
 * {$str_val|detail=data_wiki}
 * 
 * @param  void
 * @return string
 * @author 李鑫辉
 */
function detail() {

    $arr_detail = array(
                        'data_staff_basic'           => array('/attendance/data_staff_basic/detail', 550),
                        'data_company_basic'         => array('/attendance/data_company_basic/detail', 550),
                        'data_company_department'    => array('/attendance/data_company_department/detail', 550),
                        'data_company_station'       => array('/attendance/data_company_station/detail', 550),
                  );
    $arr_args   = func_get_args();
    $mix_val    = $arr_args[0];
    $str_table  = $arr_args[1];
    $int_width  = $arr_args[2] ? $arr_args[2] : 650;
    $int_height = $arr_args[3] ? $arr_args[3] : $arr_detail[$str_table][1];

    return '<a href="' . $arr_detail[$str_table][0] . '?id=' . $mix_val . '" target="dialog" width="' . $int_width . '" height="' . $int_height . '" rel="' . $str_table . '_detail">' . $mix_val . '</a>';
}

/**
 * Get user name
 * 
 * @param  $intUserId
 * @return string
 * @author andy
 */
function get_user_name( $intUserId ) {
    
    return User::get_user_name($intUserId);
}

/**
 * Get login user id
 * 
 * @param  void
 * @return string
 * @author andy
 */
function get_login_user_id() {
    
    return User::get_login_user_id();
}

/**
 * Get login user name
 * 
 * @param  void
 * @return string
 * @author andy
 */
function get_login_user_name() {
    
    return User::get_login_user_name();
}